package me.zhengjie.modules;

import com.alibaba.fastjson.JSON;
import me.zhengjie.modules.utils.LogUtils;
import me.zhengjie.modules.wrap.CustomHttpServletRequestWrapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class GlobalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Enumeration<String> parameterNames = request.getParameterNames();
        Map<String, Object> requestParams = new HashMap<>();

        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            requestParams.put(name, request.getParameter(name));
        }
        CustomHttpServletRequestWrapper wrapper = (CustomHttpServletRequestWrapper) request;
        String bodyParams = wrapper.getBody();
        String url = request.getRequestURL().toString();
        if (!url.endsWith("showQRCode") && !url.endsWith("showBarCode") && !url.endsWith("jpg") && !url.endsWith("png")) {
            LogUtils.writeToFile(request.getRequestURL().toString() + " " + request.getMethod()
                    + "   Params: " + JSON.toJSONString(requestParams)
                    + "   Body: " + bodyParams);
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        CustomHttpServletResponseWrapper wrapper = (CustomHttpServletResponseWrapper) response;
//        String result = wrapper.getBody();
//        LogUtils.writeToFile(result);

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


}
